package com.example.interview.reflex;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-04-02
 * Time:16:33
 * Text：
 */
public class Test {
    public static void getPublicMethod() throws Exception{
        // 1.反射得到对象
        Class<?> clazz = Class.forName("reflex.User");
        // 2.得到公共方法
        Method method = clazz.getDeclaredMethod("publicMethod");
        // 3.执行公共方法
        method.invoke(clazz.getDeclaredConstructor().newInstance());
    }
    public static void getPrivateMethod() throws Exception {
        // 1.反射得到对象
        Class<?> clazz = Class.forName("reflex.User");
        // 2.得到方法
        Method method = clazz.getDeclaredMethod("publicMethod");
        // 得到私有方法
        Method privateMethod = clazz.getDeclaredMethod("privateMethod");
        // 设置私有方法可访问
        privateMethod.setAccessible(true);
        // 执行私有方法
        privateMethod.invoke(clazz.getDeclaredConstructor().newInstance());

    }
    public static void getStaticMethod() throws Exception{
        // 1.反射得到对象
        Class<?> clazz = Class.forName("reflex.User");
        // 2.得到方法
        Method method = clazz.getDeclaredMethod("publicMethod");
        // 得到静态方法
        Method staticMethod = clazz.getDeclaredMethod("staticMethod");
         // 执行静态方法
        staticMethod.invoke(clazz);
    }
    public static void getFiledMethod() throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 反射得到对象
        Class<?> clazz = Class.forName("reflex.User");
        // 得到公共属性
        Field field = clazz.getDeclaredField("name");
        // 得到属性值
        String name = (String) field.get(
                clazz.getDeclaredConstructor().newInstance());
        // 打印属性值
        System.out.println("name -> " + name);

    }
    public static void getPrivateMethod2() throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> clazz = Class.forName("reflex.User");

        Field field = clazz.getDeclaredField("age");

        field.setAccessible(true);

        int age = (int) field.get(clazz.getDeclaredConstructor().newInstance());

    }
    public static void main(String[] args) throws Exception{
        getPublicMethod();
        getPrivateMethod();
         getPrivateMethod2();
    }
}
